package market

import (
	"encoding/json"
	"errors"
	"fmt"
	"igxe-change/model"
	"io/ioutil"
	"net/http"
	"sort"
	"strings"
)

type StoreResult struct {
	Status  int32
	Data    StoreData
	Message string
}

type StoreItem struct {
	Id          int
	ItemId      int    `json:"item_id"`
	ProductType string `json:"product_type"`
	Price       float64
	Name        string
}

type StoreData struct {
	List []StoreItem
}

var baseUrl = "https://open.c5game.com"

func GetItemFromStore(name string) (StoreItem, error) {
	url := fmt.Sprintf("%s/v1/store?appid=%d&keyword=%s", baseUrl, 570, name)

	resp, err := http.Get(url)

	var storeItem StoreItem

	if err != nil {
		return storeItem, err
	}

	defer resp.Body.Close()
	content, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		return storeItem, err
	}

	var result StoreResult

	json.Unmarshal(content, &result)
	if result.Status != 200 {
		return storeItem, errors.New(result.Message)
	}

	for _, item := range result.Data.List {
		if strings.TrimSpace(item.Name) == strings.TrimSpace(name) &&
			item.ProductType == "S" {
			storeItem = item
			break
		}
	}

	return storeItem, nil
}

func GetMedianHistoryPrice(itemId int) (float64, error) {
	url := fmt.Sprintf("%s/v1/store/item/history?ios_version_code=10800&item_id=%d", baseUrl, itemId)

	response, err := http.Get(url)

	if err != nil {
		return 0.0, err
	}

	defer response.Body.Close()

	var result model.StoreHistoryResult

	content, err := ioutil.ReadAll(response.Body)

	if err != nil {
		return 0.0, err
	}

	json.Unmarshal(content, &result)

	items := result.Data.List

	if len(items) == 0 {
		return 0.0, errors.New("获取数据为空")
	}

	sort.Slice(items, func(i, j int) bool {
		return items[i].PayMoney > items[j].PayMoney
	})

	mIndex := len(items) / 2

	money := items[mIndex].PayMoney

	return money, nil
}
